<?php if (!defined('THINK_PATH')) exit(); /*a:3:{s:87:"D:\vue\xiangcun\ruoyi\webeditor\web/../source/application/admin\view\settings\roles.php";i:1749140811;s:85:"D:\vue\xiangcun\ruoyi\webeditor\source\application\admin\view\layout\layui_header.php";i:1760207975;s:85:"D:\vue\xiangcun\ruoyi\webeditor\source\application\admin\view\layout\layui_footer.php";i:1750747208;}*/ ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo (isset($title) && ($title !== '')?$title:'精简版权限管理系统'); ?> - 管理后台</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link href="/assets/common/css/layui.css" rel="stylesheet">
    <link rel="stylesheet" href="/assets/common/font-awesome.min.css">
    <style>
        /* 自定义样式补充 */
        .layui-logo {
            color: #fff;
            font-size: 18px;
            font-weight: bold;
        }
        
        .layui-nav-tree .layui-nav-item > a {
            height: 50px;
            line-height: 50px;
        }
        
        .layui-nav-tree .layui-nav-child dd a {
            height: 40px;
            line-height: 40px;
        }
        
        .layui-body {
            overflow-y: auto;
        }
        
        .main-content {
            padding: 20px;
            min-height: calc(100vh - 140px);
        }
        
        .page-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0 0 8px 0;
        }
        
        .page-subtitle {
            color: #666;
            font-size: 14px;
            margin: 0;
        }
        
        .widget {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .widget-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .widget-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }
        
        .widget-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-widget {
            padding: 6px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            color: #666;
            text-decoration: none;
            font-size: 12px;
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .btn-widget:hover {
            background: #1890ff;
            color: #fff;
            border-color: #1890ff;
        }
        
        /* 移动端适配 */
        @media (max-width: 768px) {
            .main-content {
                padding: 15px;
            }
            
            .widget {
                padding: 15px;
            }
            
            .widget-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .widget-actions {
                width: 100%;
            }
            
            .btn-widget {
                flex: 1;
                text-align: center;
            }
            
            /* 移动端左侧菜单默认隐藏 */
            .layui-side {
                left: -200px !important;
                transition: left 0.3s ease;
                z-index: 1001;
            }
            
            /* 移动端菜单展开状态 */
            .layui-layout-admin.mobile-menu-open .layui-side,
            .layui-side.mobile-menu-open {
                left: 0 !important;
            }
            
            /* 移动端内容区域调整 */
            .layui-body {
                left: 0 !important;
                transition: margin-left 0.3s ease;
            }
            
            /* 移动端遮罩层 */
            .mobile-menu-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                z-index: 1000;
                display: none;
                opacity: 0;
                transition: opacity 0.3s ease;
            }
            
            .layui-layout-admin.mobile-menu-open .mobile-menu-overlay {
                display: block;
                opacity: 1;
            }
            
            /* 确保移动端菜单按钮可见 */
            .layui-nav .layui-nav-item[lay-header-event="menuLeft"] {
                display: inline-block !important;
            }
            
            /* 移动端菜单按钮样式 */
            .layui-nav .layui-nav-item[lay-header-event="menuLeft"] i {
                font-size: 18px;
                color: #fff;
            }
        }
        
        /* 移动端菜单按钮样式优化 */
        .layui-nav .layui-nav-item[lay-header-event="menuLeft"] {
            cursor: pointer;
        }
        
        .layui-nav .layui-nav-item[lay-header-event="menuLeft"]:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
    </style>
</head>
<body>
<script src="/assets/common/layui.js"></script>
<script>
    var $ = layui.jquery;
</script>
<div class="layui-layout layui-layout-admin">
    <!-- 头部区域 -->
    <div class="layui-header">
        <div class="layui-logo layui-hide-xs">精简版权限管理系统</div>
        <!-- 头部区域（可配合layui 已有的水平导航） -->
        <ul class="layui-nav layui-layout-left">
            <!-- 移动端显示 -->
            <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
                <i class="layui-icon layui-icon-spread-left"></i>
            </li>
            <!-- 移动端标题 -->
            <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" style="color: #fff; line-height: 60px; padding-left: 15px;">
                权限管理系统
            </li>
        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item layui-hide layui-show-sm-inline-block">
                <a href="javascript:;">
                    <i class="layui-icon layui-icon-user"></i>
                    <?php
                    use think\Session;
                    $adminInfo = Session::get('admin_info');
                    echo $adminInfo ? $adminInfo['real_name'] ?: $adminInfo['username'] : '未知用户';
                    ?>
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="<?php echo url('/admin/settings/profile'); ?>">个人信息</a></dd>
                    <dd><a href="<?php echo url('/admin/settings/changePassword'); ?>">修改密码</a></dd>
                    <dd><a href="javascript:;" id="logout-btn">退出登录</a></dd>
                </dl>
            </li>
        </ul>
    </div>
    
    <!-- 左侧导航区域 -->
    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree" lay-filter="nav">
                <?php
                use app\common\MenuHelper;
                echo MenuHelper::generateMenuHTML($current_page ?? '', $current_subpage ?? '');
                ?>
            </ul>
        </div>
    </div>
    

    
    <!-- 移动端菜单遮罩层 -->
    <div class="mobile-menu-overlay"></div>
    
    <script src="/assets/common/js/layui.js"></script>
    <script>
    // 退出登录功能
    layui.use(['layer', 'jquery'], function(){
        var layer = layui.layer;
        var $ = layui.jquery;
        
        // 退出登录
        $(document).on('click', '#logout-btn', function(e){
            e.preventDefault();
            layer.confirm('确定要退出登录吗？', {
                icon: 3,
                title: '提示'
            }, function(index){
                $.ajax({
                    url: '/admin/login/logout',
                    type: 'POST',
                    dataType: 'json',
                    success: function(res) {
                        layer.close(index);
                        if (res.code === 0) {
                            layer.msg(res.msg || '退出成功', {icon: 1, time: 1000}, function(){
                                window.location.href = res.redirect || '/admin/login';
                            });
                        } else {
                            layer.msg(res.msg || '退出失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(index);
                        layer.msg('网络错误，请稍后重试', {icon: 2});
                    }
                });
            });
            return false;
        });
    });
    </script>
    
    <!-- 内容主体区域 -->
    <div class="layui-body">

<!-- 主要内容 -->
<div class="main-content">
    <div class="page-header">
        <h1 class="page-title">角色管理</h1>
        <p class="page-subtitle">管理系统角色和权限分配</p>
    </div>

<style>
.layui-card { 
    margin-bottom: 15px; 
    box-shadow: 0 1px 2px rgba(0,0,0,0.15);
}
.stat-item { 
    text-align: center; 
    padding: 20px; 
}
.stat-value { 
    font-size: 32px; 
    font-weight: bold; 
    color: #01AAED; 
}
.stat-label { 
    margin-top: 8px; 
    color: #666; 
}
.role-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
}
.role-title {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
}
.role-actions {
    display: flex;
    gap: 8px;
}
.search-form {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 15px;
    border: 1px solid #e6e8eb;
}
.search-form .layui-form-item {
    margin-bottom: 0;
}
.search-inline {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: end;
}
.search-inline .layui-inline {
    margin: 0;
}
.table-container {
    margin-top: 0;
}
.permission-tree {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e6e8eb;
    padding: 10px;
}
.tree-node {
    padding: 5px 0;
    border-left: 2px solid transparent;
}
.tree-node.parent {
    border-left-color: #01AAED;
    background: #f8f9fa;
}
.tree-node input[type="checkbox"] {
    margin-right: 5px;
}
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 角色统计概览 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>角色概览</h3>
                </div>
                <div class="layui-card-body">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="totalRoles">0</div>
                                <div class="stat-label">总角色数</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="enabledRoles">0</div>
                                <div class="stat-label">启用角色</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="adminRoles">0</div>
                                <div class="stat-label">管理角色</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="disabledRoles">0</div>
                                <div class="stat-label">禁用角色</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 角色列表 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <div class="role-header">
                        <h3 class="role-title">角色列表</h3>
                        <div class="role-actions">
                            <button class="layui-btn layui-btn-normal" onclick="addRole()">
                                <i class="layui-icon layui-icon-add-1"></i> 添加角色
                            </button>
                            <button class="layui-btn layui-btn-primary" onclick="refreshTable()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索表单 -->
                    <div class="search-form">
                        <div class="layui-form">
                            <div class="search-inline">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 70px;">角色名称</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="searchRoleName" class="layui-input" placeholder="请输入角色名称">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 50px;">状态</label>
                                    <div class="layui-input-inline" style="width: 120px;">
                                        <select name="searchStatus">
                                            <option value="">全部</option>
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn" onclick="searchRoles()">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button class="layui-btn layui-btn-primary" onclick="resetSearch()">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 数据表格 -->
                    <div class="table-container">
                        <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<!-- 操作按钮模板 -->
<script type="text/html" id="roleBarDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="permissions">权限配置</a>
    {{# if(d.id != 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    {{# } }}
</script>

</div>
    
    <!-- 底部固定区域 -->
    <div class="layui-footer">
        © 2025 大头停车管理系统 - 智能停车解决方案
    </div>
</div>

<!-- <script src="/assets/common/layui.js"></script> -->
<script>
//JS 
layui.use(['element', 'layer', 'util'], function(){
    var element = layui.element;
    var layer = layui.layer;
    var util = layui.util;
    
    // 重新渲染元素，确保菜单正常工作
    element.render('nav');
    
    //头部事件
    util.event('lay-header-event', {
        menuLeft: function(othis){ // 左侧菜单事件 - 移动端菜单切换
            toggleMobileMenu();
        },
        menuRight: function(){  // 右侧菜单事件
            layer.open({
                type: 1,
                title: '更多',
                content: '<div style="padding: 15px;">处理右侧面板的操作</div>',
                area: ['260px', '100%'],
                offset: 'rt', // 右上角
                anim: 'slideLeft', // 从右侧抽屉滑出
                shadeClose: true,
                scrollbar: false
            });
        }
    });
    
    // 移动端菜单控制函数
    function toggleMobileMenu() {
        var $layout = $('.layui-layout-admin');
        var $side = $('.layui-side');
        var $overlay = $('.mobile-menu-overlay');
        
        console.log('toggleMobileMenu 被调用');
        
        if ($layout.hasClass('mobile-menu-open')) {
            // 关闭菜单
            $layout.removeClass('mobile-menu-open');
            $side.removeClass('mobile-menu-open');
            console.log('关闭移动端菜单');
        } else {
            // 打开菜单
            $layout.addClass('mobile-menu-open');
            $side.addClass('mobile-menu-open');
            console.log('打开移动端菜单');
        }
    }
    
    // 点击遮罩层关闭菜单
    $(document).on('click', '.mobile-menu-overlay', function() {
        console.log('点击遮罩层关闭菜单');
        $('.layui-layout-admin').removeClass('mobile-menu-open');
        $('.layui-side').removeClass('mobile-menu-open');
    });
    
    // 监听窗口大小变化，当屏幕变大时自动关闭移动端菜单
    $(window).on('resize', function() {
        if ($(window).width() > 768) {
            console.log('屏幕变大，关闭移动端菜单');
            $('.layui-layout-admin').removeClass('mobile-menu-open');
            $('.layui-side').removeClass('mobile-menu-open');
        }
    });
    
    // 添加移动端菜单项点击后自动关闭菜单的功能
    $(document).on('click', '.layui-side .layui-nav a', function(e) {
        if ($(window).width() <= 768) {
            var href = $(this).attr('href');
            if (href && href !== 'javascript:;' && href.indexOf('#') !== 0) {
                setTimeout(function() {
                    $('.layui-layout-admin').removeClass('mobile-menu-open');
                    $('.layui-side').removeClass('mobile-menu-open');
                }, 200);
            }
        }
    });
    
    // 设置当前页面导航高亮
    var currentPath = window.location.pathname;
    var currentUrl = window.location.href;
    
    // 获取当前页面的控制器和方法
    var urlParams = new URLSearchParams(window.location.search);
    var currentController = '';
    var currentAction = '';
    
    // 解析URL参数中的s参数（如：/admin/park）
    if (urlParams.get('s')) {
        var sParam = urlParams.get('s');
        var parts = sParam.split('/');
        if (parts.length >= 3) {
            currentController = parts[2]; // admin后面的控制器名
            currentAction = parts[3] || 'index'; // 方法名，默认index
        }
    } else {
        // 如果没有s参数，从路径中解析
        var pathParts = currentPath.split('/');
        if (pathParts.length >= 3) {
            currentController = pathParts[2];
            currentAction = pathParts[3] || 'index';
        }
    }
    
    console.log('当前控制器:', currentController, '当前方法:', currentAction);
    
    // 遍历所有菜单项进行匹配
    $('.layui-nav-tree a').each(function(){
        var $this = $(this);
        var href = $this.attr('href');
        var isMatched = false;
        
        if (href && href !== 'javascript:;') {
            // 处理完整URL匹配
            if (href.indexOf('http') === 0) {
                if (currentUrl === href) {
                    isMatched = true;
                }
            } else {
                // 处理相对路径匹配
                if (href.indexOf('?s=') !== -1) {
                    // 解析href中的s参数
                    var hrefUrl = new URL(href, window.location.origin);
                    var hrefS = hrefUrl.searchParams.get('s');
                    if (hrefS) {
                        var hrefParts = hrefS.split('/');
                        if (hrefParts.length >= 3) {
                            var hrefController = hrefParts[2];
                            var hrefAction = hrefParts[3] || 'index';
                            
                            // 精确匹配控制器
                            if (currentController === hrefController) {
                                // 如果是同一个控制器，进一步检查方法
                                if (hrefAction === 'index' || currentAction === hrefAction) {
                                    isMatched = true;
                                }
                            }
                        }
                    }
                } else {
                    // 传统路径匹配
                    if (currentPath.indexOf(href) === 0) {
                        isMatched = true;
                    }
                }
            }
        }
        
        if (isMatched) {
            $this.parent().addClass('layui-this');
            $this.parents('.layui-nav-item').addClass('layui-nav-itemed');
            console.log('匹配到菜单:', href);
        }
    });
    
    // 监听导航点击事件，确保菜单正常工作
    element.on('nav(nav)', function(elem){
        // 菜单点击事件处理
        console.log('菜单点击：', elem);
    });
    
    // 确保所有有子菜单的项目都能正常展开
    $('.layui-nav-tree .layui-nav-item').each(function(){
        var $this = $(this);
        if($this.find('.layui-nav-child').length > 0){
            $this.find('> a').off('click').on('click', function(e){
                e.preventDefault();
                
                // 切换展开状态
                if($this.hasClass('layui-nav-itemed')){
                    $this.removeClass('layui-nav-itemed');
                } else {
                    $this.addClass('layui-nav-itemed');
                }
                
                return false;
            });
        }
    });
});
</script>
</body>
</html>

<script>
layui.use(['table', 'form', 'layer', 'tree'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var tree = layui.tree;

    // 初始化表格
    table.render({
        elem: '#roleTable',
        url: '/admin/settings/getRoleList',
        height: 'full-200',
        page: true,
        loading: true,
        parseData: function(res) {
            // 更新统计数据
            if (res.data && res.data.length > 0) {
                updateStats(res.data, res.count);
            }
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count,
                "data": res.data
            };
        },
        cols: [[
            {field: 'role_name', title: '角色名称', width: 120},
            {field: 'role_code', title: '角色代码', width: 120},
            {field: 'description', title: '角色描述', width: 200},
            {field: 'user_count', title: '用户数量', width: 100, align: 'center'},
            {field: 'permission_count', title: '权限数量', width: 100, align: 'center'},
            {field: 'status', title: '状态', width: 80, templet: function(d){
                return d.status == 1 ? '<span style="color: #5FB878;">启用</span>' : '<span style="color: #FF5722;">禁用</span>';
            }},
            {field: 'sort_order', title: '排序', width: 80, align: 'center'},
            {field: 'created_at', title: '创建时间', width: 160},
            {title: '操作', width: 220, toolbar: '#roleBarDemo'}
        ]]
    });

    // 监听工具条
    table.on('tool(roleTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            editRole(data.id);
        } else if(obj.event === 'del'){
            deleteRole(data.id, data.role_name);
        } else if(obj.event === 'permissions'){
            configPermissions(data.id, data.role_name);
        }
    });

    // 更新统计数据
    function updateStats(data, total) {
        var enabled = 0, admin = 0, disabled = 0;
        
        data.forEach(function(role) {
            if (role.status == 1) enabled++;
            if (role.status == 0) disabled++;
            if (role.role_code.indexOf('admin') >= 0) admin++;
        });
        
        $('#totalRoles').text(total);
        $('#enabledRoles').text(enabled);
        $('#adminRoles').text(admin);
        $('#disabledRoles').text(disabled);
    }

    // 搜索角色
    window.searchRoles = function() {
        table.reload('roleTable', {
            where: {
                role_name: $('input[name="searchRoleName"]').val(),
                status: $('select[name="searchStatus"]').val()
            }
        });
    };

    // 重置搜索
    window.resetSearch = function() {
        $('input[name="searchRoleName"]').val('');
        $('select[name="searchStatus"]').val('');
        form.render('select');
        table.reload('roleTable', {
            where: {}
        });
    };

    // 刷新表格
    window.refreshTable = function() {
        table.reload('roleTable');
    };

    // 添加角色
    window.addRole = function() {
        showRoleForm('添加角色', {});
    };

    // 编辑角色
    window.editRole = function(id) {
        $.get('/admin/settings/getRoleDetail', {id: id}, function(res) {
            if (res.code === 0) {
                showRoleForm('编辑角色', res.data);
            } else {
                layer.msg('获取角色信息失败：' + res.msg, {icon: 2});
            }
        });
    };

    // 显示角色表单
    function showRoleForm(title, role) {
        var isEdit = role.id ? true : false;
        var html = '<div style="padding: 20px;">' +
            '<form class="layui-form" lay-filter="roleForm">' +
            (isEdit ? '<input type="hidden" name="id" value="' + role.id + '">' : '') +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色名称 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="role_name" lay-verify="required" placeholder="请输入角色名称" class="layui-input" value="' + (role.role_name || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色代码 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="role_code" lay-verify="required" placeholder="请输入角色代码(英文)" class="layui-input" value="' + (role.role_code || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色描述</label>' +
                '<div class="layui-input-block">' +
                    '<textarea name="description" placeholder="请输入角色描述" class="layui-textarea">' + (role.description || '') + '</textarea>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">排序</label>' +
                '<div class="layui-input-block">' +
                    '<input type="number" name="sort_order" placeholder="请输入排序（数字越小越靠前）" class="layui-input" value="' + (role.sort_order || 0) + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">状态</label>' +
                '<div class="layui-input-block">' +
                    '<select name="status">' +
                        '<option value="1" ' + (role.status == 1 ? 'selected' : '') + '>启用</option>' +
                        '<option value="0" ' + (role.status == 0 ? 'selected' : '') + '>禁用</option>' +
                    '</select>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                    '<button type="submit" class="layui-btn" lay-submit lay-filter="submitRole">保存</button>' +
                    '<button type="reset" class="layui-btn layui-btn-primary">重置</button>' +
                '</div>' +
            '</div>' +
            '</form>' +
            '</div>';

        layer.open({
            type: 1,
            title: title,
            content: html,
            area: ['500px', '550px'],
            success: function(layero, index) {
                form.render();
                
                // 监听表单提交
                form.on('submit(submitRole)', function(data) {
                    var url = isEdit ? '/admin/settings/editRole' : '/admin/settings/addRole';
                    
                    $.post(url, data.field, function(res) {
                        if (res.code === 0) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                            table.reload('roleTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    });
                    
                    return false;
                });
            }
        });
    }

    // 删除角色
    window.deleteRole = function(id, roleName) {
        layer.confirm('确定要删除角色 "' + roleName + '" 吗？', function(index) {
            $.post('/admin/settings/deleteRole', {id: id}, function(res) {
                if (res.code === 0) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('roleTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
                layer.close(index);
            });
        });
    };

    // 配置权限
    window.configPermissions = function(roleId, roleName) {
        $.when(
            $.get('/admin/settings/getPermissionTree'),
            $.get('/admin/settings/getRolePermissions', {role_id: roleId})
        ).done(function(treeRes, permRes) {
            if (treeRes[0].code === 0 && permRes[0].code === 0) {
                showPermissionConfig(roleId, roleName, treeRes[0].data, permRes[0].data);
            } else {
                layer.msg('获取权限数据失败', {icon: 2});
            }
        });
    };

    // 显示权限配置弹窗
    function showPermissionConfig(roleId, roleName, permissionTree, selectedIds) {
        var html = '<div style="padding: 20px;">' +
            '<div class="layui-form">' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色名称：</label>' +
                '<div class="layui-input-block" style="line-height: 38px;">' + roleName + '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">选择权限：</label>' +
                '<div class="layui-input-block">' +
                    '<div id="permissionTree" class="permission-tree"></div>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                    '<button type="button" class="layui-btn" onclick="savePermissions(' + roleId + ')">保存配置</button>' +
                    '<button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>' +
                '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        layer.open({
            type: 1,
            title: '权限配置 - ' + roleName,
            content: html,
            area: ['600px', '600px'],
            success: function(layero, index) {
                // 渲染权限树
                tree.render({
                    elem: '#permissionTree',
                    data: permissionTree,
                    showCheckbox: true,
                    id: 'permissionTreeDemo',
                    isJump: false,
                    click: function(obj) {
                        // 处理点击事件
                    }
                });
                
                // 设置选中状态
                setTimeout(function() {
                    tree.setChecked('permissionTreeDemo', selectedIds);
                }, 100);
                
                // 全局保存权限函数
                window.savePermissions = function(roleId) {
                    // 使用layui tree的getChecked方法获取选中的节点
                    var checkedData = tree.getChecked('permissionTreeDemo');
                    var permissionIds = [];
                    
                    // 调试信息
                    console.log('权限树选中数据:', checkedData);
                    
                    // 如果checkedData是数组，直接遍历
                    if (Array.isArray(checkedData)) {
                        checkedData.forEach(function(item) {
                            permissionIds.push(item.id);
                            console.log('选中权限:', item.id, item.title);
                        });
                    } else {
                        // 如果不是数组，尝试从树结构中获取所有选中的节点
                        var treeData = layui.tree.getChecked('permissionTreeDemo');
                        
                        // 递归获取所有选中的权限ID（包括子节点）
                        function getCheckedIds(nodes) {
                            if (!nodes || !Array.isArray(nodes)) return;
                            nodes.forEach(function(node) {
                                if (node.checked) {
                                    permissionIds.push(node.id);
                                    console.log('选中权限:', node.id, node.title);
                                }
                                if (node.children && node.children.length > 0) {
                                    getCheckedIds(node.children);
                                }
                            });
                        }
                        
                        // 如果上面的方法还是不行，尝试直接从DOM获取选中状态
                        if (permissionIds.length === 0) {
                            $('#permissionTree input[type="checkbox"]:checked').each(function() {
                                var $checkbox = $(this);
                                var $node = $checkbox.closest('[data-id]');
                                if ($node.length > 0) {
                                    var nodeId = $node.attr('data-id');
                                    if (nodeId && permissionIds.indexOf(nodeId) === -1) {
                                        permissionIds.push(nodeId);
                                        console.log('从DOM获取选中权限:', nodeId);
                                    }
                                }
                            });
                        }
                    }
                    
                    console.log('最终权限ID数组:', permissionIds);
                    
                    // 如果没有选中任何权限，也要发送请求（清空权限）
                    $.post('/admin/settings/assignPermissions', {
                        role_id: roleId,
                        permission_ids: permissionIds
                    }, function(res) {
                        console.log('服务器响应:', res);
                        if (res.code === 0) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                            table.reload('roleTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }).fail(function(xhr, status, error) {
                        console.error('请求失败:', xhr.responseText);
                        layer.msg('请求失败，请检查网络连接', {icon: 2});
                    });
                };
            }
        });
    }
});
</script> 